package com.currentcms.client.component;

import com.currentcms.client.IValue;
import com.currentcms.client.StyleNames;
import com.currentcms.client.event.DeleteEvent;
import com.currentcms.client.event.DeleteHandler;
import com.currentcms.client.event.HasDeleteHandlers;
import com.currentcms.client.event.HasSelectHandlers;
import com.currentcms.client.event.SelectEvent;
import com.currentcms.client.event.SelectHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.DoubleClickEvent;
import com.google.gwt.event.dom.client.DoubleClickHandler;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.FocusPanel;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.Widget;

public class ListItem<T> extends FocusPanel implements IValue<T>, HasSelectHandlers<T>, HasDeleteHandlers
{

    private final HandlerManager handlerManager = new HandlerManager(this);

    private T userObject;

    private SimplePanel panel;

    private Button deleteButton;

    public ListItem(boolean deletable)
    {
        setStyleName(StyleNames.CLASS_LIST_ITEM);

        addDomHandler(new DoubleClickHandler()
        {
            @Override
            public void onDoubleClick(DoubleClickEvent pEvent)
            {
                handlerManager.fireEvent(new SelectEvent<T>(ListItem.this, getValue()));
            }
        }, DoubleClickEvent.getType());

        FlowPanel hp = new FlowPanel();
        panel = new SimplePanel();
        panel.setStyleName(StyleNames.CLASS_LIST_ITEM_CONTENT);
        hp.add(panel);
        if(deletable)
        {
            deleteButton = new Button();
            deleteButton.setStyleName("delete-Button");
            deleteButton.addClickHandler(new ClickHandler()
            {
                @Override
                public void onClick(ClickEvent event)
                {
                    handlerManager.fireEvent(new DeleteEvent(ListItem.this));
                }
            });
            hp.add(deleteButton);
        }
        super.setWidget(hp);
    }
    
    public Button getDeleteButton()
    {
        return deleteButton;
    }

    public void setValue(T o)
    {
        userObject = o;
    }

    public T getValue()
    {
        return userObject;
    }

    public void setWidget(Widget w)
    {
        panel.setWidget(w);
    }

    @Override
    public HandlerRegistration addSelectHandler(SelectHandler<T> handler)
    {
        return handlerManager.addHandler(SelectEvent.getType(), handler);
    }

    @Override
    public HandlerRegistration addDeleteHandler(DeleteHandler handler)
    {
        return handlerManager.addHandler(DeleteEvent.getType(), handler);
    }

}
